package com.ericsson.enap.modules.kpi.task.ims;

import com.ericsson.common.quartz.task.ManualTask;
import com.ericsson.common.util.DateUtils;
import com.ericsson.common.util.FormulaConvert;
import com.ericsson.common.util.LogFileName;
import com.ericsson.common.util.LoggerUtils;
import com.ericsson.enap.modules.kpi.entity.EnipFormula;
import com.ericsson.enap.modules.kpi.entity.ImsNbiKpi;
import com.ericsson.enap.modules.kpi.service.IEnipFormulaService;
import com.ericsson.enap.modules.kpi.service.ImsNbiKpiService;
import com.ericsson.enap.modules.kpi.thread.KpiDataProcessImsNbiThread;
import com.ericsson.enap.modules.sys.entity.EpcDict;
import com.ericsson.enap.modules.sys.service.EpcDictService;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.*;

/**
 * ims NBI ry-vue指标处理
 */
@Component
public class ImsNbiKpiTask implements ManualTask {
    private Logger log = LoggerUtils.Logger(LogFileName.ImsNbiKpiJob);

    @Autowired
    private IEnipFormulaService enipFormulaService;
    @Autowired
    private ImsNbiKpiService imsNbiKpiService;
    @Autowired
    private EpcDictService epcDictService;

    @Value("${imskpiDownloadDir}")
    private String imskpiDownloadDir;
    @Value("${baseDir}")
    private String baseDir;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${collectorIp}")
    private String collectorIp;

    @Override
    public void execute() {
        Date now = new Date();
        //删除过期数据
        deleteMongodbData(now);
        //查询NBI网元 ims nettype 4:NBI
        ImsNbiKpi imsNbiKpi = null;
        List<ImsNbiKpi> imsNbiKpis = imsNbiKpiService.findImsNbiKpiList(collectorIp);
        if (imsNbiKpis.size() > 0) {
            imsNbiKpi = imsNbiKpis.get(0);
        }
        //查询字典表中的IMS网元类型
        Map<String, String> imsNetTypeMap = getNetMap();
        for (String key : imsNetTypeMap.keySet()) {
            //101:PSBCC  102:TAS   103:CSCF
            List<ImsNbiKpi> imsNbiKpiList = imsNbiKpiService.findImsNbiKpiListByType(key);
            Map<String, ImsNbiKpi> imsNbiKpiMap = new HashMap<>();
            for (ImsNbiKpi imsNbiKpi1 : imsNbiKpiList) {
                imsNbiKpiMap.put(imsNbiKpi1.getNbiAlias(), imsNbiKpi1);
            }
            EnipFormula enipFormulaQuery=new EnipFormula();
            enipFormulaQuery.setBizType(8);
            enipFormulaQuery.setNetType(key);
            List<EnipFormula> enipFormulas= enipFormulaService.selectEnipFormulaList(enipFormulaQuery);
            //存储公式的空间粒度，为解析时使用，如果xml中的空间粒度不在列表中  就不解析对应的部分Measurements
            List<String> formulaUnit = new ArrayList<>();
            Map<Long, Expression> formulaExpressions = new HashMap<>();
            for (Iterator iter = enipFormulas.iterator(); iter.hasNext(); ) {
                EnipFormula f = (EnipFormula) iter.next();
                log.info("=======type======= " + imsNetTypeMap.get(key) + " =====Formula==== " + f.getFormula());
                formulaUnit.add(f.getObjtype());
                String formulaText = FormulaConvert.convertFormula(f.getFormula());
                try {
                    Expression compiledExp = AviatorEvaluator.compile(formulaText);
                    formulaExpressions.put(f.getId(), compiledExp);
                } catch (Exception e) {
                    iter.remove();
                    log.error("error====" + e.getMessage() + "====", e);
                } finally {
                    continue;
                }
            }
            String path = this.baseDir + File.separator + this.imskpiDownloadDir;
            KpiDataProcessImsNbiThread kpiDataProcessThread = new KpiDataProcessImsNbiThread(imsNbiKpi, formulaExpressions, imsNetTypeMap.get(key), enipFormulas, now, log, path, formulaUnit, imsNbiKpiMap);
            kpiDataProcessThread.run();
            // new Thread(kpiDataProcessThread).start();
        }
    }

    private Map<String, String> getNetMap() {
        Map<String, String> netMap = new HashMap<>();
        netMap.put("101", "PSBCC");
        netMap.put("102", "TAS");
        netMap.put("103", "CSCF");
        return netMap;
    }


    /**
     * 删除过期数据
     *
     * @param now
     */
    private void deleteMongodbData(Date now) {
        EpcDict epcDict = new EpcDict();
        epcDict.setKeyName("IMSKPIMONGODBTIME");
        epcDict = epcDictService.selectEpcDict(epcDict);
        if (null != epcDict && !"".equals(epcDict.getKeyValue())) {
            String deleteTime = DateUtils.getStatisTime(Integer.parseInt(epcDict.getKeyValue()) * 1440 + 30, now, "yyyy-MM-dd HH:mm:00");
            log.info("deleteTime-------------------------------:" + deleteTime);
            Query query = Query.query(Criteria.where("dateTime").lte(deleteTime));
            mongoTemplate.remove(query, "imskpi_8_cscf");
            mongoTemplate.remove(query, "imskpi_8_tas");
            mongoTemplate.remove(query, "imskpi_8_psbcc");
        }
    }
}
